package cn.lxb.web.starter.template.domain.dto;

import cn.lxb.web.starter.template.exception.ApplicationException;
import org.springframework.beans.BeanUtils;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * 转换为DTO对象
 *
 * @param <D> DTO对象类型
 * @author 54lxb
 * @since 2019-11-20
 */
public interface DefaultConvertDTO<D> extends ConvertDTO<D>  {
    /**
     * 转换
     *
     * @return DTO对象
     */
    @Override
    @SuppressWarnings("unchecked")
    default D toDTO() {
        Type[] types = getClass().getGenericInterfaces();
        Class<D> clazz = null;
        for (Type type : types) {
            if (!(type instanceof ParameterizedType)) {
                continue;
            }
            ParameterizedType parameterizedType = (ParameterizedType) type;
            Type rawType = parameterizedType.getRawType();
            if (rawType == DefaultConvertDTO.class) {
                clazz = (Class<D>) parameterizedType.getActualTypeArguments()[0];
                break;
            }
        }
        if (null == clazz) {
            return null;
        }
        try {
            D dto = clazz.newInstance();
            BeanUtils.copyProperties(this, dto);
            return dto;
        } catch (Exception e) {
            throw new ApplicationException(e.getLocalizedMessage(), e);
        }
    }
}
